from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os


class WebDriverFactory:
    """浏览器驱动工厂类（单例模式优化版）"""

    _instance = None  # 单例实例
    _driver = None  # 共享的浏览器实例

    def __new__(cls, browser_type="chrome", headless=False):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super(WebDriverFactory, cls).__new__(cls)
            cls._instance.browser_type = browser_type.lower()
            cls._instance.headless = headless
        return cls._instance

    def create_driver(self):
        """创建或返回现有的浏览器实例"""
        if WebDriverFactory._driver is None:
            print("正在初始化浏览器...")
            if self.browser_type == "chrome":
                options = Options()
                # 性能优化配置
                options.add_argument("--headless=new") if self.headless else None
                options.add_argument("--no-sandbox")
                options.add_argument("--disable-dev-shm-usage")
                options.add_argument("--disable-gpu")
                options.add_argument("--disable-extensions")
                options.add_argument("--disable-notifications")
                options.add_argument("--start-maximized")
                options.add_experimental_option("excludeSwitches", ["enable-automation"])
                options.add_experimental_option('useAutomationExtension', False)

                WebDriverFactory._driver = webdriver.Chrome(options=options)
                # 减少隐式等待时间
                WebDriverFactory._driver.implicitly_wait(3)
                print("浏览器初始化完成")
        return WebDriverFactory._driver

    def quit_driver(self):
        """关闭浏览器"""
        if WebDriverFactory._driver:
            WebDriverFactory._driver.quit()
            WebDriverFactory._driver = None
            WebDriverFactory._instance = None
            print("浏览器已关闭")


# 全局单例快捷函数
_driver_instance = None


def get_driver(browser_type="chrome", headless=False):
    """快速获取浏览器驱动（全局单例）"""
    global _driver_instance
    if _driver_instance is None:
        _driver_instance = WebDriverFactory(browser_type, headless)
    return _driver_instance.create_driver()


def quit_driver():
    """快速关闭浏览器"""
    global _driver_instance
    if _driver_instance:
        _driver_instance.quit_driver()
        _driver_instance = None